﻿using System;
using System.Diagnostics;
using Microsoft.SharePoint;
using Microsoft.PKS;

namespace ActivateHandler
{
    /// <summary>
    /// Activation Handler for the Podcasting Solution 
    /// for Microsoft SharePoint features
    /// </summary>
    public class ActivateHandler : SPFeatureReceiver
    {
        #region Member Variables
        private static readonly string loggerSource = "PKS PodcastListActivationHandler";
        private Logger logger = Logger.CreateDefaultLogger(loggerSource);
        private readonly string assemblyName = "PKS.UpdateDurationThumbnailHandler,Version=1.0.0.0, Culture=neutral, PublicKeyToken=3a737f14c332a521";
        private readonly string listReceiverName = "UpdateDurationThumbnailHandler.UpdateDurationThumbnailHandler";
        private readonly string podcastContentType = "PKS Podcast";
        #endregion

        #region Feature Activated Override

        /// <summary>
        /// Called when the feature is activated. Adds item handlers
        /// to all lists that support the PSMS Rated Item content type
        /// </summary>
        /// <param name="properties"></param>
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
			Trace.WriteLine("Entering FeatureActivated.");

            // Assume no errors
            string errorMessage = string.Empty;

            // Make sure we have something passed in for the properties
            if (properties != null && properties.Feature != null && properties.Feature.Parent != null)
            {
                // Get the site collection associated with the properties
                using (SPSite sitecollection = (SPSite)properties.Feature.Parent)
                {
                    // Make sure we have a site collection
                    if (sitecollection != null)
                    {
                        // Get the root web
                        using (SPWeb web = sitecollection.RootWeb)
                        {
                            // Make sure there is a root web
                            if (web != null)
                            {
								CreateConfigList(web);

                                // Walk through all of the web lists trying to find all
                                // of them that support our content type
                                foreach (SPList listPodcast in web.Lists)
                                {
                                    // If the list supports content types
                                    if (listPodcast.AllowContentTypes && listPodcast.ContentTypes != null && listPodcast.ContentTypes.Count > 0)
                                    {
                                        bool foundList = false;
                                        
                                        // Search for a match with our content type
                                        foreach (SPContentType contentType in listPodcast.ContentTypes)
                                        {
                                            if (contentType.Name == podcastContentType)
                                            {
                                                foundList = true;
                                                break;
                                            }
                                        }
                
                                        // See if this is one of our lists
                                        if (foundList)
                                        {
                                            // Set up for error messages
                                            bool addedItemAddedReceiver = false;
                                            bool addedItemUpdatedReceiver = false;
                                            
                                            try
                                            {
                                                // Add the ItemAdded receiver
                                                listPodcast.EventReceivers.Add(SPEventReceiverType.ItemAdded, assemblyName, listReceiverName);
                                                addedItemAddedReceiver = true;

                                                // Add the ItemUpdated receiver
                                                listPodcast.EventReceivers.Add(SPEventReceiverType.ItemUpdated, assemblyName, listReceiverName);
                                                addedItemUpdatedReceiver = true;
                                            }
                                            catch (Exception ex)
                                            {
                                                if (!addedItemAddedReceiver)
                                                {
                                                    errorMessage = String.Format("Exception occured trying to add the ItemAdded event receiver - {0}", ex.Message);
                                                }
                                                else if (!addedItemUpdatedReceiver)
                                                {
                                                    errorMessage = String.Format("Exception occured trying to add the ItemUpdated event receiver - {0}", ex.Message);
                                                }
                                            }
                                            break;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                errorMessage = "There is no root web in the site collection. Please contact your system administrator";
                            }
                        }
                    }
                    else
                    {
                        errorMessage = "The site collection is null";
                    }
                }
            }
            else
            {
                // See what went wrong and set the error message appropriately
                if (properties == null)
                {
                    errorMessage = "properties parameter was passed in as null";
                }
                else if (properties.Feature == null)
                {
                    errorMessage = "properties.Feature was passed in as null";
                }
                else
                {
                    errorMessage = "properties.Feature.Parent was passed in as null";
                }
            }
            
            // See if there was an error.
            // If so log it.
			if (errorMessage.Length > 0)
			{
				logger.Write(EventLogEntryType.Error, errorMessage);
			}

			Trace.WriteLine("Leaving FeatureActivated.");
        }

		private void CreateConfigList(SPWeb web)
		{
			Trace.WriteLine("Entering CreateConfigList.");

			try
			{
				ManagedConfigList cl = new ManagedConfigList(web);
				cl.ResetToDefaultSettings();

				string output = "Created " + ManagedConfigList.listName + ".";
				logger.Write(EventLogEntryType.Information, output);
				Trace.WriteLine(output);
			}
			catch(Exception ex)
			{
				string output = "Unable to create " + ManagedConfigList.listName + ". Exception thrown: " + ex.ToString();
				logger.Write(EventLogEntryType.Error, output);
				Trace.WriteLine(output);
			}

			Trace.WriteLine("Leaving CreateConfigList.");
		}


        #endregion

        #region Unimplemented Overrides
        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
        }
        
        
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            string deactivationMessage = "Deactivating PSMS Item Update handlers";
            string deactivatedMessage = "PSMS Item Update handlers deactivated";
            
            Logger logger = Logger.CreateDefaultLogger(loggerSource);
            logger.Write(EventLogEntryType.Information, deactivationMessage); 

            //using (SPSite sitecollection = (SPSite)properties.Feature.Parent)
            //{
            //    //register ItemAdded event handler
            //    using (SPWeb web = sitecollection.RootWeb)
            //    {
            //        SPList listPodcast = web.Lists["AcademyMobileContent"];
            //        try
            //        {
            //            //remove event receiver
            //            string eventReceiverAssemblyName = "UpdateDurationThumbnailHandler,Version=1.0.0.0, Culture=neutral, PublicKeyToken=e45326ab18add969";
            //            SPEventReceiverDefinitionCollection eventreceivers = listPodcast.EventReceivers;
            //            SPEventReceiverDefinition currentReceiver = null;
            //            for (int i = eventreceivers.Count - 1; i >= 0; i--)
            //            {
            //                currentReceiver = eventreceivers[i];
            //                if (currentReceiver.Assembly == eventReceiverAssemblyName)
            //                {
            //                    currentReceiver.Delete();
            //                }
            //            }
            //            listPodcast.Update();
            //        }

            //        catch (Exception ex)
            //        {
            //        }
            //    }
            //}
            
            logger.Write(EventLogEntryType.Information, deactivatedMessage); 

        }
        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            //throw new NotImplementedException();
        }
        #endregion
    }
}


        
    



